package com.src.xyzk_personal;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.src.xyzk_personal.EOL.DbAdapter;
import com.src.xyzk_personal.EOL.DbAdapter.TableData;
import com.src.xyzk_personal.EOL.DbAdapter.TableMain;
import com.src.xyzk_personal.config.Common;
import com.src.xyzk_personal.config.HttpRequest;
import com.src.xyzk_personal.config.Message;
import com.src.xyzk_personal.config.MyProgressBar;
import com.src.xyzk_personal.config.ServerSocket;
import com.src.xyzk_personal.config.WifiAdmin;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Service;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UpdateDataActivity extends Activity {
	private static String TAG = "UpdateDataActivity";
	Context context = UpdateDataActivity.this;
	//锁定屏幕
	private PowerManager powerManager = null;
	private WakeLock wakeLock = null;

	//设置
	private Spinner m_printselect = null;	//下拉菜单
	private ArrayList<String> m_printarray = null;
	private ArrayAdapter<String> m_printadapter = null;
	//通讯方式
	private Spinner m_comselect = null;	//下拉菜单
	private ArrayList<String> m_comarray = null;
	private ArrayAdapter<String> m_comadapter = null;
	private ProgressDialog progressdialog;
	//时间设置
	int [] m_end_time = new int[6];
	private TextView m_endtime = null;
	private EditText m_vin = null;	// vin码
	private Button m_search = null;
	private TextView m_startdate = null;
	private TextView m_starttime = null;
	private TextView m_enddate = null;
	int [] m_start_time = new int[6];
	private UpdataEOL m_thread = null; //执行线程
	private ListView m_listdata = null;
	private ArrayList<Map<String, String>> m_listdataArray = null;
	private ListSearchAdapter m_listdata_adapter = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.updatedata_activity);
		//锁定屏幕初始化
		powerManager = (PowerManager) this.getSystemService(Service.POWER_SERVICE);
		wakeLock = this.powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Lock");
		//todo 初始化界面
		InitView();
		//是否需计算锁的数量
		wakeLock.setReferenceCounted(false);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//请求常亮
		wakeLock.acquire();
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		//取消屏幕常亮
		wakeLock.release();
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	void InitView()
	{
		//edit
		m_vin = (EditText)findViewById(R.id.system_edit_vin);
		//button
		m_search = (Button) findViewById(R.id.system_search);
		//start
		m_startdate = (TextView) findViewById(R.id.system_get_start_date);
		m_starttime = (TextView) findViewById(R.id.system_get_start_time);
		m_enddate = (TextView) findViewById(R.id.system_get_end_date);
		m_endtime = (TextView) findViewById(R.id.system_get_end_time);
		//初始化
		for(int k = 0; k < 6; k ++)
		{
			m_start_time[k] = 0;
			m_end_time[k] = 0;
		}
		m_startdate.setText(m_start_time[0] + "-" + m_start_time[1] + "-" + m_start_time[2] + "");
		m_enddate.setText(m_end_time[0] + "-" + m_end_time[1] + "-" + m_end_time[2] + "");
		m_endtime.setText(m_end_time[3] + ":" + m_end_time[4] + ":" + m_end_time[5] + "");
		m_endtime.setText(m_end_time[3] + ":" + m_end_time[4] + ":" + m_end_time[5] + "");
		//列表初始化
		m_listdata = (ListView)findViewById(R.id.system_show_list);
		m_listdataArray = new ArrayList<Map<String,String>>();
		m_listdata_adapter = new ListSearchAdapter(m_listdataArray);
		m_listdata.setAdapter(m_listdata_adapter);
		m_listdata.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
				//TODO 上传数据
				m_listdataArray.get(position).get(TableMain.ID); //主表id
				String update = m_listdataArray.get(position).get(TableMain.update);
				if (update.equals("已上传")){
					//弹窗界面
					final MsgWaitDialog waitdialog = new MsgWaitDialog(UpdateDataActivity.this);
					waitdialog.setText("上传单条数据?");
					waitdialog.setWaitTime(0);
					waitdialog.ShowCancel();
					waitdialog.show();
					waitdialog.setOnOKButton(new OnClickListener() {
						@Override
						public void onClick(View v) {
							waitdialog.dismiss();
							//执行功能
							progressdialog = ProgressDialog.createDialog(context,"上传数据中...");
							//上传数据线程
							StartDiagnose(Integer.parseInt(m_listdataArray.get(position).get(TableMain.ID)), Integer.parseInt(m_listdataArray.get(position).get(TableMain.testnum)),
									m_listdataArray.get(position).get(TableMain.vin));
						}
					});
				}
			}
		});
	}
	public void StartDiagnose(int id,int testNUM,String vin)
	{
		//启动线程
		m_thread = new UpdataEOL(id, testNUM,vin);
		if(Common.Debug) Log.i(TAG,"启动线程...");
		m_thread.start();
	}
	private class UpdataEOL extends Thread{
		int id=0;
		int testNUM=0;
		String vin = "";
		public UpdataEOL(int id,int testNUM,String vin) {
			this.id = id;
			this.testNUM = testNUM;
			this.vin = vin;
		}
		@Override
		public void run(){
			Map<String,String> querymap = new HashMap<>();
			List<Map<String,String>> queryList = new ArrayList<>();
			DbAdapter db = new DbAdapter(context);
			db.open();
			//查询主表数据
			querymap = db.selectforIDQuery(id);
			//查询子表数据
			queryList = db.querysubdataforvin(vin,testNUM);
			//上传数据
			SendWebData(querymap,queryList);
			if (Common.updata_isok==true){
				db.updatemaintable(id);
				//todo 更新界面
			}
			db.close();
			//制作加载界面
		}
	}

	//封装 上传数据的方法
	private void SendWebData(Map mainmap,List sublist) {
		//上传web服务器
		JSONObject jsonmain = new JSONObject();
		try {
			jsonmain.put("resultVin",mainmap.get(DbAdapter.TableMain.vin));
			jsonmain.put("resultCar",mainmap.get(DbAdapter.TableMain.car));
			jsonmain.put("resultCartype",mainmap.get(DbAdapter.TableMain.cartype));
			jsonmain.put("resultStation",mainmap.get(DbAdapter.TableMain.station));
			jsonmain.put("resultCarname",mainmap.get(DbAdapter.TableMain.carname));
			jsonmain.put("resultCardate",mainmap.get(DbAdapter.TableMain.timestart));
			jsonmain.put("resultCartime",mainmap.get(DbAdapter.TableMain.timeend));
			jsonmain.put("resultDevice",mainmap.get(DbAdapter.TableMain.device));
			String station = mainmap.get(DbAdapter.TableMain.station).toString();
			if (station.indexOf("-")>0){
				jsonmain.put("resultPrintnum","99");
			}else jsonmain.put("resultPrintnum",Common.Printnum);
			jsonmain.put("resultTestnum",mainmap.get(DbAdapter.TableMain.testnum));
			jsonmain.put("resultResult",mainmap.get(DbAdapter.TableMain.result));
			jsonmain.put("resultPrint",mainmap.get(DbAdapter.TableMain.printdata));
			jsonmain.put("resultPin",mainmap.get(DbAdapter.TableMain.pin));
			jsonmain.put("resultEsk",mainmap.get(DbAdapter.TableMain.esk));
			jsonmain.put("resultAppver",mainmap.get(DbAdapter.TableMain.appversion));
			//未启用
			jsonmain.put("resultColor",mainmap.get(DbAdapter.TableMain.carcolor));
			jsonmain.put("resultUp2mes","0");
			jsonmain.put("resultUser","test");

			jsonmain.put("fileName",mainmap.get(DbAdapter.TableMain.logfileName));
			jsonmain.put("resultLog",mainmap.get(DbAdapter.TableMain.logpath));
			JSONArray array=new JSONArray();
			for(int k = 0; k < sublist.size(); k ++)
			{

				Map submap = (Map) sublist.get(k);
				JSONObject jsondetail = new JSONObject();
				jsondetail.put("mVin",mainmap.get(DbAdapter.TableMain.vin));
				jsondetail.put("mTestcode",submap.get(DbAdapter.TableData.testcode));
				jsondetail.put("mContext",submap.get(DbAdapter.TableData.context));
				jsondetail.put("mTestdata",submap.get(DbAdapter.TableData.testdata));
				jsondetail.put("mStand",submap.get(DbAdapter.TableData.teststand));
				jsondetail.put("mResult",submap.get(DbAdapter.TableData.result));
				array.put(k,jsondetail);
			}
			jsonmain.put("tableResultDetails", array);
			Long v_upfileid = (long) 0;
			for(int k = 0; k < 3; k ++)
			{
				String res = HttpRequest.sendPostToMyMes(Common.Web_Result_Add, jsonmain.toString().replace(">",""));
				if(res.indexOf("200") > 0) //ok
				{
					JSONObject resjson = new JSONObject(res);
					JSONObject son = resjson.getJSONObject("data");
					if(son != null)
						v_upfileid = son.getLong("resultId");
					break;
				}else {
					Common.updata_isok=false;
				}
			}
			//上传日志文件
			if(v_upfileid > 0) {
				uploadFiles(Common.Web_Result_Uploadfile, (String) mainmap.get(DbAdapter.TableMain.logpath), v_upfileid);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//  上传日志文件
	/**
	 * 文件上传线程
	 * @param uploadUrl
	 * @param filePaths
	 * @param id
	 */

	public void uploadFiles(String uploadUrl, String filePaths,Long id)
	{
		MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
		String fname = filePaths;
		File tempfile = new File(fname);
		//根据文件的后缀名，获得文件类型
		builder.setType(MultipartBody.FORM)
				.addFormDataPart("resultId", String.valueOf(id))// 其他参数信息
				.addFormDataPart( //给Builder添加上传的文件
						"files",  //请求的名字
						tempfile.getName(), //文件的文字，服务器端用来解析的
						RequestBody.create(MediaType.parse("multipart/form-data"), tempfile)//创建RequestBody，把上传的文件放入
				);
		MultipartBody requestBody = builder.build();
		Request request = new Request.Builder()
				.url(uploadUrl)
				.post(requestBody)
				.build();
		OkHttpClient client = new OkHttpClient.Builder()
				.connectTimeout(10000, TimeUnit.SECONDS)
				.readTimeout(10000, TimeUnit.SECONDS)
				.writeTimeout(10000, TimeUnit.SECONDS).build();
		client.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Call call, final IOException e) {
				Log.e("TAG", "返回内容===失败>:" + e.toString());
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String result = response.body().string();
				Log.e("TAG", "返回内容===成功>:" + result);
			}
		});
	}
	public class ListSearchAdapter extends BaseAdapter
	{
		private ArrayList<Map<String, String>> listdata = null;
		private SystemListShow listshow = null;
		private View view = null;
		private LayoutInflater inflater = null;
		private int Selected = -1;
		public ListSearchAdapter(ArrayList<Map<String, String>> Pdata) {
			// TODO Auto-generated constructor stub
			listdata = Pdata;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if(listdata != null)
				return listdata.size();
			else
				return 0;
		}
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			if(listdata != null && listdata.size() > position)
				return listdata.get(position);
			else
				return null;
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		public void setSelected(int pos)
		{
			Selected = pos;
		}
		public int getSelected()
		{
			return Selected;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = inflater.inflate(R.layout.dbdata_search_listview, null, false);
			listshow = (SystemListShow) view.getTag();
			if(listshow == null)
			{
				listshow = new SystemListShow();
				listshow.id = (TextView)view.findViewById(R.id.data_search_list_id);
				listshow.vin = (TextView)view.findViewById(R.id.data_search_list_vin);
				listshow.station = (TextView)view.findViewById(R.id.data_search_list_station);
				listshow.car = (TextView)view.findViewById(R.id.data_search_list_car);
				listshow.color = (TextView)view.findViewById(R.id.data_search_list_color);
				listshow.time = (TextView)view.findViewById(R.id.data_search_list_time);
				listshow.testnum = (TextView)view.findViewById(R.id.data_search_list_testnum);
				listshow.result = (TextView)view.findViewById(R.id.data_search_list_result);
				listshow.up = (TextView)view.findViewById(R.id.data_search_list_up);
				listshow.user = (TextView)view.findViewById(R.id.data_search_list_user);
				view.setTag(listshow);
			}
//			if(listdata.get(position).get("RESULT").equals("2"))
//			{
//				view.setBackgroundColor(Color.RED);
//			}
//			else if(position == Selected)
//			{
//				//listlayout.text.setBackgroundColor(Color.GREEN);
//				view.setBackgroundColor(Color.GREEN);
//				listshow.id.setSelected(true);
//				listshow.id.setPressed(true);
//			}
//			else if(position % 2 == 1)
//			{
//				listshow.id.setSelected(false);
//				listshow.id.setPressed(false);
//				view.setBackgroundColor(0xFFC0C0C0);
//			}
//			else
//			{
//				listshow.id.setSelected(false);
//				listshow.id.setPressed(false);
//				view.setBackgroundColor(Color.WHITE);
//			}
			listshow.id.setText(listdata.get(position).get(TableMain.ID));
			listshow.vin.setText(listdata.get(position).get(TableMain.vin));
			listshow.station.setText(listdata.get(position).get(TableMain.station));
			listshow.car.setText(listdata.get(position).get(TableMain.car));
			listshow.color.setText(listdata.get(position).get(TableMain.carcolor));
			listshow.time.setText(listdata.get(position).get(TableMain.timestart));
			listshow.testnum.setText(listdata.get(position).get(TableMain.testnum));
			listshow.result.setText(listdata.get(position).get(TableMain.result));
			listshow.up.setText(listdata.get(position).get(TableMain.update));
			listshow.user.setText("");
			return view;
		}
	}
	class SystemListShow
	{
		TextView id;
		TextView vin;
		TextView station;
		TextView car;
		TextView color;
		TextView time;
		TextView testnum;
		TextView result;
		TextView up;
		TextView user;
	}

	public void SetStartDate(View v) {

		new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
								  int dayOfMonth) {
				m_start_time[0] = year;
				m_start_time[1] = monthOfYear + 1;
				m_start_time[2]= dayOfMonth;
				m_startdate.setText(m_start_time[0] + "-" + m_start_time[1] + "-" + m_start_time[2] );
			}
		}, 2022, 02, 19).show();

	}
	public void SetStartTime(View v) {
		new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				m_start_time[3] = hourOfDay;
				m_start_time[4] = minute;
				m_start_time[5] = 0;
				m_starttime.setText(m_start_time[3] + ":" + m_start_time[4] + ":" + m_start_time[5] + "");
			}
		}, 00, 00, true).show();

	}
	public void SetEndDate(View v) {

		new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
								  int dayOfMonth) {
				m_end_time[0] = year;
				m_end_time[1] = monthOfYear + 1;
				m_end_time[2]= dayOfMonth;
				m_enddate.setText(m_end_time[0] + "-" + m_end_time[1] + "-" + m_end_time[2]);
			}
		}, 2022, 02, 19).show();

	}
	public void SetEndTime(View v) {
		new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				m_end_time[3] = hourOfDay;
				m_end_time[4] = minute;
				m_end_time[5] = 0;
				m_endtime.setText(m_end_time[3] + ":" + m_end_time[4] + ":" + m_end_time[5] + "");
			}
		}, 00, 00, true).show();

	}
	//查询数据
	public void SearchData(View v) {
		//先检测条件
		if(m_vin.getText().toString().length() == 17) //有VIN
		{
		} else  //按时间,判断时间
		{
			if(m_start_time[0] == 0 || m_end_time[0] == 0) //未设置
			{
				Toast.makeText(context, "请设置起止时间！", Toast.LENGTH_LONG).show();
				return;
			}
		}
		m_listdataArray.clear();

		DbAdapter db = new DbAdapter(context);
		db.open();
		// todo 数据查询，并更新界面
		List<Map<String, String>> list= db.TablemainQuery(m_vin.getText().toString(),m_starttime.toString(),m_endtime.toString());
		if(list != null)
		{
			for(int k = 0; k < list.size(); k ++) m_listdataArray.add(list.get(k));
			m_listdata_adapter.notifyDataSetChanged();
		}
		db.close();

	}
}
